import config from '@/config/app.js';
import cache from './cache.js';
import util from './util';

/**
 * 发送请求
 */
function baseRequest(url, requestData, method, {
	noAuth = false,
	noVerify = false
}) {
	let baseURL = config.HTTP_REQUEST_URL,
		header = config.HEADER,
		token = cache.get(config.LOGIN_TOKEN, false) || '',
		requestUrl = '/api/' + url;

	console.log('Token', token);
	console.log('请求地址', requestUrl);
	/* if (!noAuth) {
		// 登录过期自动登录
		if (!token) {
			cache.logOut();
			util.toLogin();
			// return Promise.reject({
			// 	msg: `未登录`
			// });
		}
	} */

	if (token) {
		header[config.TOKENNAME] = token;
		requestData.token = token;
		requestData.role = 0;
	}

	header['Auth-Role'] = 0;

	return new Promise((reslove, reject) => {
		uni.request({
			url: baseURL + requestUrl,
			method: method,
			header: header,
			data: requestData,
			success: (res) => {
				// console.log('请求响应', res);
				if (noVerify) {
					reslove(res.data, res);
				} else if (res.statusCode == 200) {
					// console.log('响应数据', res.data);
					reslove(res.data, res);
				} else if (res.statusCode == 401) {
					//未授权，重新登录
					cache.logOut();
					util.toLogin();
					reslove(res.data, res);
				} else if (res.statusCode == 403) {
					let data = {
						mag: `无权限访问`,
						code: 403
					}
					reslove(data, res);
				} else if (res.statusCode == 404) {
					let data = {
						mag: `访问错误`,
						code: 404
					}
					reslove(data, res);
				} else {
					let data = {
						mag: `系统错误`,
						code: 500
					}
					reslove(data, res);
				}
			},
			fail: (msg) => {
				let data = {
					mag: `请求失败`,
					code: 1 //1没网
				}
				reject(data);
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, data || {}, method, opt || {})
});

export default request;